package com.speedchina.oauth2_permission.utils;

import com.speedchina.framework.utils.ApplicationContextHolder;
import com.speedchina.permission.domain.sys.entity.User;
import com.speedchina.permission.service.sys.UserService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.token.TokenService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * SecurityUtils
 *
 * @author Winter
 * @create 2020-11-12 下午4:03
 **/

public class SecurityUtils {

    /**
     * 获取当前登录用户
     * @return
     */
    public static User getLoginUser() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
//        Authentication authentication =SecurityContextHolder.getContext().getAuthentication();
//        org.springframework.security.core.userdetails.User u = (org.springframework.security.core.userdetails.User)(authentication);
        BearerTokenExtractor bearerTokenExtractor = new BearerTokenExtractor();
        UserService userService = ApplicationContextHolder.getBean(UserService.class);
        ResourceServerTokenServices tokenService = ApplicationContextHolder.getBean(ResourceServerTokenServices.class);
        Authentication authentication = bearerTokenExtractor.extract(servletRequestAttributes.getRequest());
        OAuth2Authentication oAuth2Authentication = tokenService.loadAuthentication((String)authentication.getPrincipal());
        return userService.getByUserName(oAuth2Authentication.getName());
    }

    /**
     * 登出
     */
    public static boolean logout() {
        return true;
    }
    /**
     * 当前用户token
     */
    public static String getToken() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        BearerTokenExtractor bearerTokenExtractor = new BearerTokenExtractor();
        return (String) bearerTokenExtractor.extract(request).getPrincipal();
    }

}
